﻿using SuperX.Common;
using SuperX.Common.BasicService;
using SuperX.Common.Helper;
using SuperX.Common.Log;
using SuperX.DataService.Abstract;
using SuperX.DeviceService;
using SuperX.DeviceService.Model;
using SuperX.WebSocketService.Server;
using System;
using System.Collections.Concurrent;
using System.Linq;
using System.Threading.Tasks;

namespace SuperX.WebSocketService
{
    public class SocketManager
    {
        private WebSocketConfig WebSocketConfig { get; set; }

        private FleckServer server { get; set; }
        private ConcurrentDictionary<string, IBasicObject> _appObjects = BasicServiceManager.GetProjService().Project.Objects;

        public SocketManager(WebSocketConfig config)
        {
            WebSocketConfig = config;
            Init();
        }

        public void Init()
        {
            try
            {
                server = new FleckServer($"ws://{WebSocketConfig.SocketServer.IP}:{WebSocketConfig.SocketServer.Port}");
            }
            catch (Exception ex)
            {
                Logger.Exception(ex);
            }
        }

        public void Start()
        {
            GetRuntimeTags();
            server?.FleckStart();
        }

        public void Stop()
        {
            Task.Factory.StartNew(() => server.Dispose());
        }

        private void GetRuntimeTags()
        {
            if (_appObjects.ContainsKey("IntergrationServer"))
            {
                var intergration = _appObjects["IntergrationServer"] as DeviceServer;
                var tags = intergration.DataManager.TagsKey.Keys;
                if (tags == null || !tags.Any()) return;
                Logger.Info($"WebSocket当前配置变量数：{tags.Count}");
                foreach (var tagkey in tags)
                {
                    if (_appObjects.ContainsKey(tagkey))
                    {
                        var tag = _appObjects[tagkey] as ITag;
                        tag.ValueChanged += OnValueChanged;
                    }
                }
            }
        }

        private void OnValueChanged(object sender, TagChangedEventArgs e)
        {
            RunTimeTagModel runTimeTagModel = new RunTimeTagModel();
            var tag = sender as IIOTag;
            var toBeSend = new RunTimeTagModel
            {
                Name = tag.Name,
                Value = tag.Value,
                FullName = tag.FullName,
                Timestamp = tag.TimeStamp,
                Address = tag.Address.Addr,
                DataType = tag.Address.VarType,
                QualityStamp = tag.Quality.ToString(),
                WriteValue = tag.RawValue,
                WriteQuality = tag.WriteQuality.ToString(),
                Unit = tag.Unit,
                Description = tag.Description,
            };
            server?.BroadcastInfo(JsonHelper.TransferObjectJsonSerialize(toBeSend, false), toBeSend.FullName);
        }
    }
}